package com.runssnail.demo.kafka;

import com.runssnail.demo.kafka.jms.MessageDecoder;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.serializer.StringDecoder;
import kafka.utils.VerifiableProperties;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @author zhengwei
 */
public class ConsumerTest {

    ConsumerConnector consumer;

    public ConsumerTest() {
        Properties props = new Properties();
        // zookeeper 配置
        props.put("zookeeper.connect", "localhost:2181");

        // group 代表一个消费组
        props.put("group.id", "jd-group");

        // zk连接超时
//      props.put("zookeeper.session.timeout.ms", "4000");

        // How far a ZK follower can be behind a ZK leader
//        props.put("zookeeper.sync.time.ms", "200");

        // The frequency in ms that the consumer offsets are committed to zookeeper.
        props.put("auto.commit.interval.ms", "10000"); //  10s

//        props.put("auto.offset.reset", "largest"); // largest or smallest

        ConsumerConfig config = new ConsumerConfig(props);

        consumer = kafka.consumer.Consumer.createJavaConsumerConnector(config);
    }

    public static void main(String[] args) {

        new ConsumerTest().consume();
    }

    public ConsumerConnector getConsumerConnector() {
        return this.consumer;
    }

    void consume() {
        Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
        topicCountMap.put(ProducerTest.TOPIC, new Integer(1));

        StringDecoder keyDecoder = new StringDecoder(new VerifiableProperties());
//        StringDecoder valueDecoder = new StringDecoder(new VerifiableProperties());

        MessageDecoder valueDecoder = new MessageDecoder();

        Map<String, List<KafkaStream<String, Object>>> consumerMap = consumer.createMessageStreams(topicCountMap,
                keyDecoder,
                valueDecoder);
        KafkaStream<String, Object> stream = consumerMap.get(ProducerTest.TOPIC).get(0);
        ConsumerIterator<String, Object> it = stream.iterator();
        while (it.hasNext()) // 没有消息的话，这里会阻塞
            System.out.println(it.next().message());
    }
}
